<?php


/**
 * 获取活动列表
 *
 * @access  public
 *
 * @return void
 */
function  get_sql_snatchlist(){
        /* 查询条件 */
        $filter['keywords']   		= 	empty($_REQUEST['keywords']) ? '' : trim($_REQUEST['keywords']);
        if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1){
            $filter['keywords'] 	= 	$filter['keywords'];
        }
        $filter['sort_by']    		= 	empty($_REQUEST['sort_by']) ? 'act_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] 		= 	empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        $where 						= 	(!empty($filter['keywords'])) ? " AND act_name like '%". Utils::mysql_like_quote($filter['keywords']) ."%'" : '';

        /* 获活动数据 */
        $sql 						= 	"SELECT act_id, act_name AS snatch_name, goods_name, start_time, end_time, is_finished, ext_info, product_id ".
               							" FROM " . 'ybr_goods_activity' .
               							" WHERE act_type = " . GAT_SNATCH . $where .
               							" ORDER by $filter[sort_by] $filter[sort_order] ";
   		return $sql;
}



/**
 * 取商品的货品列表
 *
 * @param       mixed       $goods_id       单个商品id；多个商品id数组；以逗号分隔商品id字符串
 * @param       string      $conditions     sql条件
 *
 * @return  array
 */
function get_good_products($goods_id, $conditions = ''){
    if (empty($goods_id)){
        return array();
    }

    switch (gettype($goods_id)){
        case 'integer':
            $_goods_id 	= 	"goods_id = '" . intval($goods_id) . "'";
        break;
        case 'string':
        case 'array':
            $_goods_id 	= 	db_create_in($goods_id, 'goods_id');
        break;
    }

    /* 取货品 */
    $sql 				=	 "SELECT * FROM " . 'ybr_products' . " WHERE $_goods_id $conditions";
    $result_products 	= 	 M()->query($sql);

    /* 取商品属性 */
    $sql 				= 	"SELECT goods_attr_id, attr_value FROM " .'ybr_goods_attr' . " WHERE $_goods_id";
    
    Log::write('Snatch : ' . $sql, 1);
    
    $result_goods_attr 	= 	M()->query($sql);

    $_goods_attr 		= 	array();
    foreach ($result_goods_attr as $value){
        $_goods_attr[$value['goods_attr_id']] 	= 	$value['attr_value'];
    }

    
    /* 过滤货品 */
    foreach ($result_products as $key => $value){
        $goods_attr_array 			= 	explode('|', $value['goods_attr']);
        if (is_array($goods_attr_array)){
            $goods_attr 			= 	array();
            foreach ($goods_attr_array as $_attr){
                $goods_attr[] 		= 	$_goods_attr[$_attr];
            }
            $goods_attr_str 		= 	implode('，', $goods_attr);
        }
        $result_products[$key]['goods_attr_str'] = $goods_attr_str;
    }
    return $result_products;
}

/**
 * 取得商品列表：用于把商品添加到组合、关联类、赠品类
 * @param   object  $filters    过滤条件
 */
function get_goods_list($filter){
    $filter['keyword']	= 	$filter['keyword'];
    $where 				= 	get_where_sql($filter); // 取得过滤条件
    
    //t($filter);
    //echo $where;

    /* 取得数据 */
    $sql = 'SELECT goods_id, goods_name, shop_price '.
           'FROM ' . 'ybr_goods' . ' AS g ' . $where .
           'LIMIT 50';    
    //echo $sql;    
    $row 				= 	M()->query($sql);
    return $row;
}

/**
 * 生成过滤条件：用于 get_goodslist 和 get_goods_list
 * @param   object  $filter
 * @return  string
 */
function get_where_sql($filter){
    $time 		= 	date('Y-m-d');

    $where  	= 	isset($filter['is_delete']) && $filter['is_delete'] == '1' ?' WHERE is_delete = 1 ' : ' WHERE is_delete = 0 ';
    $where 		.= 	(isset($filter['real_goods']) && ($filter['real_goods'] > -1)) ? ' AND is_real = ' . intval($filter['real_goods']) : '';
    $where 		.= 	isset($filter['cat_id']) && $filter['cat_id'] > 0 ? ' AND ' . get_children($filter['cat_id']) : '';
    $where 		.= 	isset($filter['brand_id']) && $filter['brand_id'] > 0 ? " AND brand_id = '" . $filter['brand_id'] . "'" : '';
    $where 		.=	isset($filter['intro_type']) && $filter['intro_type'] != '0' ? ' AND ' . $filter['intro_type'] . " = '1'" : '';
    $where 		.= 	isset($filter['intro_type']) && $filter['intro_type'] == 'is_promote' ?
        			" AND promote_start_date <= '$time' AND promote_end_date >= '$time' " : '';
    $where 		.= 	isset($filter['keyword']) && trim($filter['keyword']) != '' ?
        			" AND (goods_name LIKE '%" . Utils::mysql_like_quote($filter['keyword']) . "%' OR goods_sn LIKE '%" . Utils::mysql_like_quote($filter['keyword']) . "%' OR goods_id LIKE '%" . Utils::mysql_like_quote($filter['keyword']) . "%') " : '';
    $where 		.= 	isset($filter['suppliers_id']) && trim($filter['suppliers_id']) != '' ?
        			" AND (suppliers_id = '" . $filter['suppliers_id'] . "') " : '';

    $where 		.= 	isset($filter['in_ids']) ? ' AND goods_id ' . db_create_in($filter['in_ids']) : '';
    $where 		.=	isset($filter['exclude']) ? ' AND goods_id NOT ' . db_create_in($filter['exclude']) : '';
    $where 		.= 	isset($filter['stock_warning']) ? ' AND goods_number <= warn_number' : '';
    return $where;
}

/**
 * 取得品牌列表
 * @return array 品牌列表 id => name
 */
function get_brand_list(){
    $sql 		= 	'SELECT brand_id, brand_name FROM ' . 'ybr_brand' . ' ORDER BY sort_order';
    $res 		= 	M()->query($sql);

    $brand_list = 	array();
    foreach ($res AS $row){
        $brand_list[$row['brand_id']] = addslashes($row['brand_name']);
    }
    return $brand_list;
}

/**
 * 获取指定id snatch 的信息
 *
 * @access  public
 * @param   int         $id         snatch_id
 *
 * @return array       array(snatch_id, snatch_name, goods_id,start_time, end_time, min_price, integral)
 */
function get_snatch_info($id){
	
	$CommonModel	=	new CommonModel();	
    $sql 			= 	"SELECT act_id, act_name AS snatch_name, goods_id, product_id, goods_name, start_time, end_time, act_desc, ext_info" .
           				" FROM " . 'ybr_goods_activity' .
           				" WHERE act_id='$id' AND act_type = " . GAT_SNATCH;
    $snatch 		= 	$CommonModel->GetRow($sql);

    /* 将时间转成可阅读格式 */
    $snatch['start_time'] 	= 	local_date('Y-m-d H:i', $snatch['start_time']);
    $snatch['end_time']   	= 	local_date('Y-m-d H:i', $snatch['end_time']);
    $row 					= 	unserialize($snatch['ext_info']);
    unset($snatch['ext_info']);
    if ($row){
        foreach ($row as $key=>$val){
            $snatch[$key] = $val;
        }
    }
    return $snatch;
}

/**
 * 取商品的下拉框Select列表
 *
 * @param       int      $goods_id    商品id
 *
 * @return  array
 */
function get_good_products_select($goods_id){
    $return_array 	= 	array();
    $products 		= 	get_good_products($goods_id);
	
    if (empty($products)){
        return $return_array;
    }
    foreach ($products as $value){
        $return_array[$value['product_id']] 	= 	$value['goods_attr_str'];
    }
    return $return_array;
}


/**
 * 返回活动详细列表
 *
 * @access  public
 *
 * @return array
 */
function get_sql_snatch_detail(){
	
	$CommonModel			=	new CommonModel();
	
    $filter['snatch_id']  	= 	empty($_REQUEST['snatch_id']) ? 0 : intval($_REQUEST['snatch_id']);
    $filter['sort_by']    	= 	empty($_REQUEST['sort_by']) ? 'bid_time' : trim($_REQUEST['sort_by']);
    $filter['sort_order'] 	= 	empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

    $where 					= 	empty($filter['snatch_id']) ? '' : " WHERE snatch_id='$filter[snatch_id]'";

    /* 获得活动数据 */
    $sql 					= 	"SELECT s.log_id, u.user_name, s.bid_price, s.bid_time ".
            					" FROM " . 'ybr_snatch_log' . " AS s ".
            					" LEFT JOIN ".'ybr_users' . " AS u ON s.user_id = u.user_id  ". $where.
            					" ORDER by ".$filter['sort_by']." ".$filter['sort_order'];
    $row 					= 	$CommonModel->query($sql);

    return $sql;
}


/**
 * 获取指定 id snatch 活动的结果
 *
 * @access  public
 * @param   int   $id       snatch_id
 *
 * @return  array           array(user_name, bie_price, bid_time, num)
 *                          num通常为1，如果为2表示有2个用户取到最小值，但结果只返回最早出价用户。
 */
function get_snatch_result($id){
	
	$CommonModel	=	new CommonModel();	
    $sql 			= 	'SELECT u.user_id, u.user_name, u.email, lg.bid_price, lg.bid_time, count(*) as num' .
            			' FROM ' . 'ybr_snatch_log' . ' AS lg '.
            			' LEFT JOIN ' . 'ybr_users' . ' AS u ON lg.user_id = u.user_id'.
            			" WHERE lg.snatch_id = '$id'".
            			' GROUP BY lg.bid_price' .
            			' ORDER BY num ASC, lg.bid_price ASC, lg.bid_time ASC LIMIT 1';
    $rec 			= 	$CommonModel->getRow($sql);

    //echo $sql.'<br/>';
    
    
    if ($rec){
        $rec['bid_time']  			= 	local_date($GLOBALS['_CFG']['time_format'], $rec['bid_time']);
        $rec['formated_bid_price'] 	= 	price_format($rec['bid_price'], false);

        /* 活动信息 */
        $sql 		= 	'SELECT ext_info " .
               			" FROM ' . 'ybr_goods_activity' .
               			" WHERE act_id= '$id' AND act_type=" . GAT_SNATCH.
               			" LIMIT 1";
        $row 		= 	$CommonModel->getOne($sql);
        $info 		= 	unserialize($row);

        if (!empty($info['max_price'])){
            $rec['buy_price'] = ($rec['bid_price'] > $info['max_price']) ? $info['max_price'] : $rec['bid_price'];
        }
        else{
            $rec['buy_price'] = $rec['bid_price'];
        }
        /* 检查订单 */
        $sql	 	= 	"SELECT COUNT(*)" .
                		" FROM " . 'ybr_order_info' .
                		" WHERE extension_code = 'snatch'" .
                		" AND extension_id = '$id'" .
                		" AND order_status " . db_create_in(array(OS_CONFIRMED, OS_UNCONFIRMED));

        $rec['order_count'] 	= 	$CommonModel->getOne($sql);
    }
    return $rec;
}






